package com.tjp.eight.ui.fragment.tabme;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.iflytek.cloud.thirdparty.V;
import com.tjp.eight.LoginEvent;
import com.tjp.eight.R;
import com.tjp.eight.RxBus;
import com.tjp.eight.constant.UrlConstant;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.ui.fragment.homepage.HomePageActivity;
import com.tjp.eight.ui.fragment.loginreg.ActivityLogin;
import com.tjp.eight.ui.fragment.modyname.ModifyNameEvent;
import com.tjp.eight.ui.fragment.personsetting.PicEvent;
import com.tjp.eight.ui.fragment.personsetting.SexEvent;
import com.tjp.eight.utils.ActivityUtils;
import com.tjp.eight.utils.BitmapUtils;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.CircleImageView;

import org.hamcrest.core.Is;

import java.util.ArrayList;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/2/13.
 */

public class FragmentMe extends BaseFragment<MePresenter> implements MeView {
    private RelativeLayout rl_me_my_msg;
    private RelativeLayout rl_my_like;
    private RelativeLayout rl_my_comment;
    private RelativeLayout rl_integration;
    private RelativeLayout rl_my_money;
    private RelativeLayout rl_my_wallet;
    private RelativeLayout rl_person_setting;
    private RelativeLayout rl_setting;
    private RelativeLayout rl_my_collection;
    private RelativeLayout rl_jf_shop;
    private RelativeLayout rl_rock;
    private RelativeLayout rl_head_right;
    private ImageView iv_head_right;
    private TextView tv_me_user_name;
    private TextView tv_me_tip;
    private TextView tv_sign;
    private TextView tv_sign_1;
    private TextView tv_sign_2;
    private TextView tv_sign_3;
    private TextView tv_sign_4;
    private TextView tv_sign_5;
    private TextView tv_sign_6;
    private TextView tv_sign_7;
    private ArrayList<TextView> signArray;
    private CircleImageView civ_me_user_pic;
    private ImageView iv_me_mm;
    private Observable<LoginEvent> observable;
    private Observable<ModifyNameEvent> observableName;
    private Observable<SexEvent> observableSex;
    private Observable<PicEvent> observablePic;

    private TextView tv_my_msg;
    private TextView tv_my_comment;
    private TextView tv_my_money;
    private TextView tv_my_collect;

    private TextView tv_new_tips;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);

        if (contentView == null) {
            contentView = inflater.inflate(R.layout.frag_me_layout, container, false);
        }

        initViews();
        registerObservable();
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (StringUtils.isNullOrEmpty(SharePreferencesUtils.getUid())) return;
        presenter.loadData(getPJson());
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    protected MePresenter createPresenter() {
        return new MePresenter(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegisterObservable();
    }


    private void initViews() {
        iv_me_mm = (ImageView) contentView.findViewById(R.id.iv_me_mm);
        TextView tvTitle = (TextView) contentView.findViewById(R.id.tv_title);
        tv_my_msg = (TextView) contentView.findViewById(R.id.tv_my_msg);
        tv_my_comment = (TextView) contentView.findViewById(R.id.tv_my_comment);
        tv_my_money = (TextView) contentView.findViewById(R.id.tv_my_money);
        tv_my_collect = (TextView) contentView.findViewById(R.id.tv_my_collect);
        tv_new_tips = (TextView) contentView.findViewById(R.id.tv_new_tips);
        tvTitle.setText("我的");
        rl_head_right = (RelativeLayout) contentView.findViewById(R.id.rl_head_right);
        iv_head_right = (ImageView) contentView.findViewById(R.id.iv_head_right);
        rl_head_right.setVisibility(View.VISIBLE);
        iv_head_right.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.service_icon_t));
        rl_head_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startWeb(getActivity(), "客服", UrlConstant.SERVICE_URL);
            }
        });
        rl_rock = (RelativeLayout) contentView.findViewById(R.id.rl_rock);
        rl_rock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!SharePreferencesUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), ActivityLogin.class);
                    startActivityForResult(intent, 0x01);
                } else
                    ActivityUtils.startRock(getActivity());
            }
        });
        RelativeLayout rl_my_home_page = (RelativeLayout) contentView.findViewById(R.id.rl_my_home_page);
        rl_my_home_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin())
                    startActivity(new Intent(getActivity(), HomePageActivity.class));
                else
                    ActivityUtils.startLoginForResult(getActivity());
            }
        });

        rl_me_my_msg = (RelativeLayout) contentView.findViewById(R.id.rl_me_my_msg);
        rl_me_my_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin()) {
                    tv_new_tips.setVisibility(View.GONE);
                    ActivityUtils.startMyMsg(getActivity());
                } else {
                    ActivityUtils.startLoginForResult(getActivity());
                }

            }
        });
        rl_my_like = (RelativeLayout) contentView.findViewById(R.id.rl_my_like);
        rl_my_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin()) {
                    tv_new_tips.setVisibility(View.GONE);
                    ActivityUtils.startMyMsg(getActivity());
                } else {
                    ActivityUtils.startLoginForResult(getActivity());
                }
            }
        });
        rl_my_comment = (RelativeLayout) contentView.findViewById(R.id.rl_my_comment);
        rl_my_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //ActivityUtils.startMyDynamic(getActivity());
                //new Intent(getActivity(), HomePageActivity.class)
                if (SharePreferencesUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), HomePageActivity.class);
                    intent.putExtra("item", 2);
                    startActivity(intent);
                } else
                    ActivityUtils.startLoginForResult(getActivity());
            }
        });
        rl_integration = (RelativeLayout) contentView.findViewById(R.id.rl_integration);
        rl_integration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin())
                    ActivityUtils.startIntegrationTask(getActivity());
                else
                    ActivityUtils.startLoginForResult(getActivity());

            }
        });
        rl_my_money = (RelativeLayout) contentView.findViewById(R.id.rl_my_money);
        rl_my_money.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin()) {
                    // ActivityUtils.startIntegrationTask(getActivity());
                    ActivityUtils.startJinBi(getActivity());
                } else {
                    ActivityUtils.startLoginForResult(getActivity());
                }
            }
        });
        rl_my_wallet = (RelativeLayout) contentView.findViewById(R.id.rl_my_wallet);
        rl_my_wallet.setVisibility(View.GONE);
        rl_my_wallet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin()) {
                    ActivityUtils.startMyWallet(getActivity(), tv_my_money.getText().toString());
                } else {
                    ActivityUtils.startLoginForResult(getActivity());
                }
            }
        });
        rl_person_setting = (RelativeLayout) contentView.findViewById(R.id.rl_person_setting);
        rl_person_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin()) {
                    ActivityUtils.startPersonSetting(getActivity());
                } else {
                    ActivityUtils.startLoginForResult(getActivity());
                }
            }
        });
        rl_setting = (RelativeLayout) contentView.findViewById(R.id.rl_setting);
        rl_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startSetting(getActivity());
            }
        });
        rl_jf_shop = (RelativeLayout) contentView.findViewById(R.id.rl_jf_shop);
        rl_jf_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startJFShop(getActivity(), SharePreferencesUtils.getMoney());
            }
        });
        rl_my_collection = (RelativeLayout) contentView.findViewById(R.id.rl_my_collection);
        rl_my_collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ActivityUtils.startCollection(getActivity());
                if (SharePreferencesUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), HomePageActivity.class);
                    intent.putExtra("item", 4);
                    startActivity(intent);
                } else
                    ActivityUtils.startLoginForResult(getActivity());
            }
        });

        tv_me_user_name = (TextView) contentView.findViewById(R.id.tv_me_user_name);
        tv_me_tip = (TextView) contentView.findViewById(R.id.tv_me_tip);
        civ_me_user_pic = (CircleImageView) contentView.findViewById(R.id.civ_me_user_pic);
        if (SharePreferencesUtils.isLogin()) {
            login();
        } else {
            logout();
        }
        tv_sign = (TextView) contentView.findViewById(R.id.tv_sign);
        tv_sign_1 = (TextView) contentView.findViewById(R.id.tv_sign_1);
        tv_sign_2 = (TextView) contentView.findViewById(R.id.tv_sign_2);
        tv_sign_3 = (TextView) contentView.findViewById(R.id.tv_sign_3);
        tv_sign_4 = (TextView) contentView.findViewById(R.id.tv_sign_4);
        tv_sign_5 = (TextView) contentView.findViewById(R.id.tv_sign_5);
        tv_sign_6 = (TextView) contentView.findViewById(R.id.tv_sign_6);
        tv_sign_7 = (TextView) contentView.findViewById(R.id.tv_sign_7);
        tv_sign_1.setEnabled(false);
        tv_sign_2.setEnabled(false);
        tv_sign_3.setEnabled(false);
        tv_sign_4.setEnabled(false);
        tv_sign_5.setEnabled(false);
        tv_sign_6.setEnabled(false);
        tv_sign_7.setEnabled(false);
        signArray = new ArrayList<>();
        signArray.add(tv_sign_1);
        signArray.add(tv_sign_2);
        signArray.add(tv_sign_3);
        signArray.add(tv_sign_4);
        signArray.add(tv_sign_5);
        signArray.add(tv_sign_6);
        signArray.add(tv_sign_7);
        tv_sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreferencesUtils.isLogin()) {
                    presenter.sign(getSignJson());
                } else {
                    ActivityUtils.startLoginForResult(getActivity());
                }
            }
        });
    }

    private String getPJson() {
        MePModel model = new MePModel();
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private String getSignJson() {
        SignePModel model = new SignePModel();
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private void registerObservable() {
        observable = RxBus.getInstance().register(LoginEvent.class);
        observable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<LoginEvent>() {
            @Override
            public void call(LoginEvent event) {
                if (event.login) {
                    presenter.loadData(getPJson());
                    login();
                }
                if (event.logout) {
                    logout();
                    rl_my_wallet.setVisibility(View.GONE);
                }
            }
        });

        observableName = RxBus.getInstance().register(ModifyNameEvent.class);
        observableName.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<ModifyNameEvent>() {
            @Override
            public void call(ModifyNameEvent modifyNameEvent) {
                if (modifyNameEvent != null && !StringUtils.isNullOrEmpty(modifyNameEvent.getName())) {
                    tv_me_user_name.setText(modifyNameEvent.getName());
                    SharePreferencesUtils.setName(modifyNameEvent.getName());
                }
            }
        });
        observableSex = RxBus.getInstance().register(SexEvent.class);
        observableSex.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<SexEvent>() {
            @Override
            public void call(SexEvent event) {
                if (event != null && !StringUtils.isNullOrEmpty(event.getSex())) {
                    SharePreferencesUtils.setGender(event.getSex());
                    if (SharePreferencesUtils.getGender().equals("男")) {
                        iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.man_enable));
                    } else {
                        iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.woman_enable));
                    }
                }
            }
        });
        observablePic = RxBus.getInstance().register(PicEvent.class);
        observablePic.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<PicEvent>() {
            @Override
            public void call(PicEvent event) {
                if (event != null) {
                    presenter.loadData(getPJson());
                }
            }
        });
    }

    private void unRegisterObservable() {
        if (observable != null) {
            RxBus.getInstance().unregister(LoginEvent.class, observable);
        }
        if (observableName != null) {
            RxBus.getInstance().unregister(ModifyNameEvent.class, observableName);
        }
        if (observableSex != null) {
            RxBus.getInstance().unregister(SexEvent.class, observableSex);
        }
        if (observablePic != null) {
            RxBus.getInstance().unregister(PicEvent.class, observablePic);
        }
    }


    void logout() {
        iv_me_mm.setVisibility(View.GONE);
        tv_me_user_name.setText("点击登录");
        tv_me_tip.setText(R.string.tv_me_tips);
        if (SharePreferencesUtils.getGender().equals("男")) {
            iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.man_enable));
        } else {
            iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.woman_enable));
        }
        Glide.with(getContext()).load(SharePreferencesUtils.getUserUrl()).error(getResources().getDrawable(R.drawable.icon_login)).into(civ_me_user_pic);
    }

    void login() {
        iv_me_mm.setVisibility(View.VISIBLE);
        tv_me_user_name.setText(SharePreferencesUtils.getName());
        tv_me_tip.setText(R.string.tv_me_tips);
        if (SharePreferencesUtils.getGender().equals("男")) {
            iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.man_enable));
        } else {
            iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.woman_enable));
        }
        Glide.with(getContext()).load(SharePreferencesUtils.getUserUrl()).error(getResources().getDrawable(R.drawable.icon_login)).into(civ_me_user_pic);
    }

    @Override
    public void loadFail(String msg) {
        ToatUtils.toastSuccess(getContext(), msg);
    }

    @Override
    public void signSuccess(SigneRModel model) {
        if (model == null) return;
        if (IsSuccessUtils.isSuccess(model.result)) {
            tv_sign.setEnabled(false);
            tv_sign.setText("已签到");
            for (int i = 0; i < signArray.size(); i++) {
                if (i <= model.sign_continue_days - 1) {
                    signArray.get(i).setEnabled(true);
                } else {
                    signArray.get(i).setEnabled(false);
                }
            }
            ToatUtils.toastSuccess(getContext(), "签到成功");
        } else {
            ToatUtils.toastSuccess(getContext(), model.msg);
        }
    }

    @Override
    public void loadSuccess(MeModel model) {
        if (model != null) {
            if (IsSuccessUtils.isSuccess(model.result)) {
                SharePreferencesUtils.setName(model.name);
                SharePreferencesUtils.setUserUrl(model.iconurl);
                SharePreferencesUtils.setMoney(model.money + "");
                tv_me_user_name.setText("" + model.name);
                Glide.with(getContext()).load(model.iconurl).error(R.drawable.icon_login).into(civ_me_user_pic);
                if (model.sign_if_can == 1) {
                    tv_sign.setEnabled(true);
                    tv_sign.setText("签到");
                } else {
                    tv_sign.setEnabled(false);
                    tv_sign.setText("已签到");
                }
                if (model.if_show_tixian == 1) {
                    rl_my_wallet.setVisibility(View.VISIBLE);
                } else {
                    rl_my_wallet.setVisibility(View.GONE);
                }
                for (int i = 0; i < signArray.size(); i++) {
                    if (i > 6) {
                        break;
                    }
                    if (i <= model.sign_continue - 1) {
                        signArray.get(i).setEnabled(true);
                    } else {
                        signArray.get(i).setEnabled(false);
                    }
                }
                tv_my_msg.setText("" + StringUtils.toWan(model.praise));
                tv_my_comment.setText("" + StringUtils.toWan(model.comment));
                tv_my_money.setText("" + StringUtils.toWan(model.money));
                tv_my_collect.setText("" + StringUtils.toWan(model.collect));
                SharePreferencesUtils.setCommetnTips(model.msg_if_new_comment);
                SharePreferencesUtils.setPraseTips(model.msg_if_new_praise);
                if (model.msg_if_new_comment == 1 || model.msg_if_new_praise == 1) {
                    tv_new_tips.setVisibility(View.VISIBLE);
                } else {
                    tv_new_tips.setVisibility(View.GONE);
                }
                SharePreferencesUtils.setGender(model.sex);
                if (SharePreferencesUtils.getGender().equals("男")) {
                    iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.man_enable));
                } else {
                    iv_me_mm.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.woman_enable));
                }
                tv_me_tip.setText("" + model.view);
            } else {
                ToatUtils.toastSuccess(getContext(), model.msg);
            }
        }
    }
}
